package com.qg.rta.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPObject;
import com.lzs.adx.commmon.redis.RedisUtils;
import com.lzs.adx.commmon.utils.DateUtils;
import com.qg.rta.DeviceUtil;
import com.qg.rta.cache.LocalCache;
import com.qg.rta.cache.RtaConfigLocalCache;
import com.qg.rta.constant.RedisKeyCacheConstant;
import com.qg.rta.context.HandlerReportContext;
import com.qg.rta.dto.baidu.dto.request.DeviceInfo;
import com.qg.rta.dto.baidu.dto.request.RtaApiRequest;
import com.qg.rta.dto.baidu.dto.response.ResType;
import com.qg.rta.dto.baidu.dto.response.RtaApiResponse;
import com.qg.rta.dto.hw.HwRtaRequest;
import com.qg.rta.dto.hw.HwRtaResponse;
import com.qg.rta.dto.request.RtaCommonRequest;
import com.qg.rta.modules.dto.RtaConfigDTO;
import com.qg.rta.support.ReportMappingFactory;
import com.qg.rta.support.channel.AbstractReport;
import com.qg.rta.support.mpping.AbstractReportParamsMapping;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RequestMapping("/rta/base")
@RestController
@Slf4j
@RequiredArgsConstructor
public class RtaBaseController {


    @Autowired
    private HandlerReportContext handlerReportContext;

    @Autowired
    private RedisUtils redisUtils;




    /**
     * 0-过滤当前流量
     * 1-选择当前流量
     * 异常
     * @param params
     * @param request
     * @return
     */
    @RequestMapping("/req")
    public int baseReport(@RequestParam Map<String,Object> params, HttpServletRequest request){

        String jsonString = JSON.toJSONString(params);
//        log.info("wifi请求rta的请求参数为{}", jsonString);
        String rtaId= String.valueOf(params.get("rtaId"));

        String day = DateUtils.getCurrentTime();
        String day_rta_req_key = String.format(RedisKeyCacheConstant.day_rta_req_key, rtaId, day);
        redisUtils.incr(day_rta_req_key,48);

        RtaConfigDTO rtaConfigDTO = RtaConfigLocalCache.getInstance().get(rtaId);

        AbstractReportParamsMapping reportParamsMapping= ReportMappingFactory.handler(rtaConfigDTO.getMediaCode());
        RtaCommonRequest adapter = reportParamsMapping.adapter(params);
        if(DeviceUtil.getDeviceId(adapter)){
            String day_rta_empty_key = String.format(RedisKeyCacheConstant.day_rta_empty_key, rtaId, day);
            redisUtils.incr(day_rta_empty_key,48);
            return 0;
        }

        AbstractReport report = handlerReportContext.getReport(rtaConfigDTO.getProductCode());

        //rta的请求
        if(report.rtaReq(adapter, rtaConfigDTO)){
            String day_rta_comp_key = String.format(RedisKeyCacheConstant.day_rta_comp_key, rtaId, day);
            redisUtils.incr(day_rta_comp_key,48);
            return 1;
        }else{
            return 0;
        }
    }



    /**
     * 0-过滤当前流量
     * 1-选择当前流量
     * 异常
     * @param params
     * @param request
     * @return
     */
    @RequestMapping("/wifi/req")
    public int report(@RequestParam Map<String,Object> params, HttpServletRequest request){
        StopWatch stopWatch=new StopWatch("快手RTA");
        try {
            stopWatch.start("1.开始跑KJBRTA");

            LocalCache localCache = LocalCache.getInstance();
            if(!params.containsKey("rtaId") || Objects.isNull(params.get("rtaId"))){
                return 0;
            }

            String rtaId= String.valueOf(params.get("rtaId"));


            String day = DateUtils.getCurrentTime();
            String day_rta_req_key = String.format(RedisKeyCacheConstant.day_rta_req_key, rtaId, day);
            localCache.incr(day_rta_req_key);

            RtaConfigDTO rtaConfigDTO = RtaConfigLocalCache.getInstance().get(rtaId);

            AbstractReportParamsMapping reportParamsMapping= ReportMappingFactory.handler(rtaConfigDTO.getMediaCode());
            RtaCommonRequest adapter = reportParamsMapping.adapter(params);
            if(DeviceUtil.getDeviceId(adapter)){
                String day_rta_empty_key = String.format(RedisKeyCacheConstant.day_rta_empty_key, rtaId, day);
                localCache.incr(day_rta_empty_key);
                return 0;
            }
            AbstractReport report = handlerReportContext.getReport(rtaConfigDTO.getProductCode());

            boolean result = report.rtaReq(adapter, rtaConfigDTO);

            stopWatch.stop();
            log.info(stopWatch.prettyPrint());

            //rta的请求
            if(result){
                String day_rta_comp_key = String.format(RedisKeyCacheConstant.day_rta_comp_key, rtaId, day);
                localCache.incr(day_rta_comp_key);
                return 1;
            }else{
                return 0;
            }
        }catch (Exception e){
             String jsonString = JSON.toJSONString(params);
             log.error("wifi请求rta的请求参数为{}", jsonString);
            log.error("rta系统异常，异常的错误错误为{}",e);
        }
        return 0;
    }

    /**
     * 0-过滤当前流量
     * 1-选择当前流量
     * 异常
     * @param hwRtaRequest
     * @return
     */
    @PostMapping("/hw/req")
    public HwRtaResponse report(@RequestBody HwRtaRequest hwRtaRequest){
        StopWatch stopWatch=new StopWatch("华为RTA");
        try {
            stopWatch.start("1.开始跑华为-KJB");

            LocalCache localCache = LocalCache.getInstance();
            if(CollectionUtil.isEmpty(hwRtaRequest.getRtaIdList())){
                return new HwRtaResponse(0,"no");
            }
            String rtaId = hwRtaRequest.getRtaIdList().get(0);
            Map<String,Object> params= JSON.parseObject(JSON.toJSONString(hwRtaRequest), HashMap.class);
            params.put("rtaId",rtaId);
            String day = DateUtils.getCurrentTime();
            String day_rta_req_key = String.format(RedisKeyCacheConstant.day_rta_req_key, rtaId, day);
            localCache.incr(day_rta_req_key);

            RtaConfigDTO rtaConfigDTO = RtaConfigLocalCache.getInstance().get(rtaId);

            AbstractReportParamsMapping reportParamsMapping= ReportMappingFactory.handler(rtaConfigDTO.getMediaCode());
            RtaCommonRequest adapter = reportParamsMapping.adapter(params);
            if(DeviceUtil.getDeviceId(adapter)){
                String day_rta_empty_key = String.format(RedisKeyCacheConstant.day_rta_empty_key, rtaId, day);
                localCache.incr(day_rta_empty_key);
                 return new HwRtaResponse(0,"no");
            }
            AbstractReport report = handlerReportContext.getReport(rtaConfigDTO.getProductCode());

            boolean result = report.rtaReq(adapter, rtaConfigDTO);

            stopWatch.stop();
            log.info(stopWatch.prettyPrint());

            //rta的请求
            if(result){
                String day_rta_comp_key = String.format(RedisKeyCacheConstant.day_rta_comp_key, rtaId, day);
                localCache.incr(day_rta_comp_key);
                return new HwRtaResponse(0,"yes");
            }else{
                return new HwRtaResponse(0,"no");
            }
        }catch (Exception e){
            String jsonString = JSON.toJSONString(hwRtaRequest);
            log.error("wifi请求rta的请求参数为{}", jsonString);
            log.error("rta系统异常，异常的错误错误为{}",e);
        }
        return new HwRtaResponse(0,"no");
    }




    @PostMapping(value = "/baidu/req/{rtaId}", consumes = "application/x-protobuf", produces = "application/x-protobuf")
    public RtaApiResponse report(@RequestBody RtaApiRequest rtaApiRequest, @PathVariable("rtaId") String rtaId){


        log.info("wifi请求rta的请求参数为{}", JSON.toJSONString(rtaApiRequest));

        String day = DateUtils.getCurrentTime();
        String day_rta_req_key = String.format(RedisKeyCacheConstant.day_rta_req_key, rtaId, day);
        redisUtils.incr(day_rta_req_key,48);

        RtaConfigDTO rtaConfigDTO = RtaConfigLocalCache.getInstance().get(rtaId);

        DeviceInfo deviceInfo = rtaApiRequest.getDeviceInfo();
        AbstractReport report = handlerReportContext.getReport(rtaConfigDTO.getProductCode());
        RtaCommonRequest adapter = new RtaCommonRequest();
        adapter.setRtaId(rtaId);
        adapter.setImeiSum(deviceInfo.getImeiMd5().toString());
        adapter.setOaid(deviceInfo.getOaid().toString());
        adapter.setOaidSum(deviceInfo.getOaidMd5().toString());
        adapter.setHash_android_id(deviceInfo.getAndroidIdMd5().toString());

        //rta的请求
        if(report.rtaReq(adapter, rtaConfigDTO)){
            String day_rta_comp_key = String.format(RedisKeyCacheConstant.day_rta_comp_key, rtaId, day);
            redisUtils.incr(day_rta_comp_key,48);
            RtaApiResponse.Builder builder = RtaApiResponse.newBuilder().setQid(rtaApiRequest.getQid()).setRes(ResType.ALL);
            return builder.build();
        }else{
            RtaApiResponse.Builder builder = RtaApiResponse.newBuilder().setQid(rtaApiRequest.getQid()).setRes(ResType.NONE);
            return builder.build();
        }
    }
}
